var store,grid,row=-1;
var sumStore,sumGrid,sumRow=-1;
var sSize = 4,lThan=1,bThan=10,eThan=5;
var productId = -1;
var Plant = Ext.data.Record.create([
       {name: 'productName', type: 'string'},
       {name: 'weight1'},
       {name: 'weight2'},
       {name: 'weight3'},
       {name: 'weight4'},
       {name: 'weight5'},
       {name: 'weight6'},
       {name: 'weight7'},
       {name: 'weight8'},
       {name: 'weight9'},
       {name: 'weight10'}
  ]);
var Summary = Ext.data.Record.create([
       {name: 'productName', type: 'string'},
       {name: 'price'},
       {name: 'count'},
       {name: 'total'}
  ]);
function addNew(){
	var p = new Plant({
        productName: '',
        weight1: '',
        weight2: '',
        weight3: '',
        weight4: '',
        weight5: '',
        weight6: '',
        weight7: '',
        weight8: '',
        weight9: '',
        weight10: ''
    });
    grid.stopEditing();
    store.add(p);
    //store.insert(0, p);
    grid.startEditing(store.getCount()-1, 0);
}
function calculateSummary(){
	lThan = Ext.getCmp('lThan').getValue();
	bThan = Ext.getCmp('bThan').getValue();
	eThan = Ext.getCmp('eThan').getValue();
	if(lThan == '' && bThan == '' && eThan == ''){
		Ext.Msg.alert('信息','请先填写单价信息');
		return ;
	}
	resetSummary();
	var ps = store.getRange();
	if(ps.length > 0){
		var productCount = 0;
		for(var i=0;i<ps.length;i++){
			var record = ps[i];
			var productName = record.get('productName');
			if(productName == ''){
				Ext.Msg.alert('信息','名称不能为空');
				return ;
			}
			var p = 0;
			var si = productName.replace('mm','');
			if(si<sSize){
				p = lThan;
			}
			else if(si>sSize){
				p = bThan;
			}else{
				p = eThan;
			}
			var sRecord;
			if(sumStore.query('productName',productName).length == 0){
				sRecord = new Summary({
					        productName: productName,
					        price: p,
					        count: 0,
					        total: 0
					    });
				sumStore.add(sRecord);
			}else{
				sRecord = sumStore.query('productName',productName).first();
				sRecord.set('price',p);
			}
			var weight = 0;
			for(var j=1;j<=10;j++){
				if(record.get('weight'+j) != ''){
					weight = weight + record.get('weight'+j);
					productCount++;//重量不为空，件数加1
				}
			}
			var count = parseFloat(sRecord.get('count'));
			var price = sRecord.get('price');
			count = weight+count;
			if(count.toFixed)
				count = count.toFixed(1);
			var total = count*price;
			if(total.toFixed)
				total = total.toFixed(1);
			sRecord.set('count',count);
			sRecord.set('total',total);
		}
		clearSummary();
		//更新件数
		Ext.getCmp('productCount').setValue(productCount);
	}
}

function resetSummary(){
//	var records = sumStore.getRange();
//	for(var i=0;i<records.length;i++){
//		var record = records[i];
//		record.set('total',0); 
//		record.set('count',0);
//	}
	sumStore.removeAll();
	Ext.getCmp('tCount').setValue('0.0');
	Ext.getCmp('tPrice').setValue('0.0');
	Ext.getCmp('productCount').setValue('0.0');
}
function clearSummary(){
	var records = sumStore.getRange();
	var tweight=0,tMoney=0,kind='',kindCount=0;
	for(var i=0;i<records.length;i++){
		var record = records[i];
		if(record.get('count') == 0){
			sumStore.remove(record);
		}else{
			tweight = tweight + parseFloat(record.get('count'));
			tMoney = tMoney + parseFloat(record.get('total'));
			kind = kind + record.get('productName')+',';
			kindCount++;
		}
	}
	if(kind.length > 1){
		kind = kind.substring(0, kind.length-1);
//		Ext.getCmp('productType').setValue(kindCount);
		Ext.getCmp('tCount').setValue(tweight.toFixed(1));
		Ext.getCmp('tPrice').setValue(tMoney.toFixed(1));
	}else{
//		Ext.getCmp('productType').setValue('');
		Ext.getCmp('tCount').setValue(0);
		Ext.getCmp('tPrice').setValue(0);
	}
}
function down(e){
	var key;
	key = e.getKey();
	if(key == 47){//code 47 is for '/'
		addNew();
	}
}
function clickrow(g,rowIndex,e){
	row = rowIndex;
}
function clickSumRow(g,rowIndex,e){
	sumRow = rowIndex;
}
function getPrice(productName){
	if(sumStore.query('productName',productName).length == 0){
		calculateSummary();
	}
	var record = sumStore.query('productName',productName).first();
	return record.get('price');
}
function getParams(){
	var params = [];
	params['product.outTime'] = Ext.getCmp('outTime').getValue();
	params['product.cusName'] = Ext.getCmp('cusName').getValue();
	params['product.productType'] = Ext.getCmp('productCount').getValue();
	params['product.totalWeight'] = Ext.getCmp('tCount').getValue();
	params['product.totalPrice'] = Ext.getCmp('tPrice').getValue();
	params['product.linker'] = Ext.getCmp('linker').getValue();
	params['product.phoneNo'] = Ext.getCmp('phoneNo').getValue();
	params['product.saleType'] = '3S';
	var details = store.getRange();
	var index = 0;
	for(var i=0;i<details.length;i++){
		var detail = details[i];
		var productName = detail.get('productName');
		var price = getPrice(productName);
		for(var j=1;j<=10;j++){
			var weight = detail.get('weight'+j);
			if(weight == undefined || weight == '')
				break;
			params['details['+index+'].productName'] = productName;
			params['details['+index+'].weight'] = weight;
			params['details['+index+'].price'] = price;
			index++;
		}
	}
	return params;
}
function save(){
	calculateSummary();
	var params = getParams();
	Ext.Ajax.request({
	   url: contextRootPath+'/product/save.do',
	   success: function(response,o){
		   productId = response.responseText;
		   Ext.getCmp('printBtn').setDisabled(false);
		   Ext.Msg.alert('信息','保存成功，记录id为'+productId);
	   },
	   failure: function(){
		   Ext.Msg.alert('信息','保存失败，请检查数据格式是否正确');
	   },
	   params: params
	});
}
Ext.onReady(function(){
	if(!Number.prototype.toFixed){ 
		Number.prototype.toFixed = function(n){ 
			with(Math)return round(Number(this)*pow(10,n))/pow(10,n) 
		} 
	} 
    Ext.QuickTips.init();

    // shorthand alias
    var fm = Ext.form;

    // custom column plugin example
    var checkColumn = new Ext.grid.CheckColumn({
       header: "Indoor?",
       dataIndex: 'indoor',
       width: 55
    });
    
    var scm = new Ext.grid.ColumnModel([{
           id:'productName',
           header: "名称",
           dataIndex: 'productName',
           width: 100,
           editor: new Ext.form.TextField({
               allowBlank: false
           })
        },{
           header: "单价",
           dataIndex: 'price',
           width: 60,
           align: 'left',
           editor: new fm.NumberField({
               allowBlank: false,
               allowNegative: false,
               maxValue: 100000,
               decimalPrecision:1,
               listeners:{
					'change':function(f,newValue,oldValue){
						if(sumRow != -1){
							var record = sumStore.getAt(sumRow);
							var count = record.get('count');
							record.set('total',count*newValue);
						}
					}               
               }
           })
        },{
           header: "重量",
           dataIndex: 'count',
           width: 60,
           align: 'left',
           editor: new fm.NumberField({
               allowBlank: false,
               allowNegative: false,
               maxValue: 100000,
               decimalPrecision:1
           })
        },{
           header: "小计",
           dataIndex: 'total',
           width: 60,
           align: 'left',
           editor: new fm.NumberField({
               allowBlank: false,
               allowNegative: false,
               maxValue: 100000,
               decimalPrecision:1
           })
        }
    ]);
    
    scm.defaultSortable = true;
    
    sumStore = new Ext.data.Store({
        // the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
               // records will have a "plant" tag
               record: 'summary'
           }, Summary),

        sortInfo:{field:'productName', direction:'ASC'}
    });

    // create the editor grid
    sumGrid = new Ext.grid.EditorGridPanel({
        store: sumStore,
        cm: scm,
        //renderTo: 'editor-grid',
        //width:1000,
        height:300,
        autoExpandColumn:'productName',
        title:'小计',
        frame:true,
        //plugins:checkColumn,
        clicksToEdit:1,
		trackMouseOver:false,
        disableSelection:true,
        loadMask: {msg:'正加载数据...'},
        viewConfig: {
            forceFit:true            
        }
    });
    
    sumGrid.on('rowclick',clickSumRow);
    
    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store (created below)
    var cm = new Ext.grid.ColumnModel([{
           id:'productName',
           header: "名称",
           dataIndex: 'productName',
           width: 100,
           editor: new Ext.form.ComboBox({
           		allowBlank: false,
               typeAhead: true,
               triggerAction: 'all',
               transform:'pn',
               lazyRender:true,
               listClass: 'x-combo-list-small'
           })
        },{
           header: "重量1",
           dataIndex: 'weight1',
           width: 60,
           align: 'right',
           editor: new fm.NumberField({
               allowBlank: false,
               allowNegative: false,
               maxValue: 100000,
               decimalPrecision:1
           })
        },{
           header: "重量2",
           dataIndex: 'weight2',
           width: 60,
           align: 'right',
           //renderer: 'usMoney',
           editor: new fm.NumberField({
               allowNegative: false,
               maxValue: 100000,
               decimalPrecision:1
           })
        },{
           header: "重量3",
           dataIndex: 'weight3',
           width: 60,
           align: 'right',
           //renderer: formatDate,
           editor: new fm.NumberField({
               allowNegative: false,
               maxValue: 100000,
               decimalPrecision:1
           })
        },{
           header: "重量4",
           dataIndex: 'weight4',
           width: 60,
           align: 'right',
           //renderer: formatDate,
           editor: new fm.NumberField({
               allowNegative: false,
               maxValue: 100000,
               decimalPrecision:1
           })
        },{
           header: "重量5",
           dataIndex: 'weight5',
           width: 60,
           align: 'right',
           //renderer: formatDate,
           editor: new fm.NumberField({
               allowNegative: false,
               maxValue: 100000,
               decimalPrecision:1
           })
        },{
           header: "重量6",
           dataIndex: 'weight6',
           width: 60,
           align: 'right',
           //renderer: formatDate,
           editor: new fm.NumberField({
               allowNegative: false,
               maxValue: 100000,
               decimalPrecision:1
           })
        },{
           header: "重量7",
           dataIndex: 'weight7',
           width: 60,
           align: 'right',
           //renderer: formatDate,
           editor: new fm.NumberField({
               allowNegative: false,
               maxValue: 100000,
               decimalPrecision:1
           })
        },{
           header: "重量8",
           dataIndex: 'weight8',
           width: 60,
           align: 'right',
           //renderer: formatDate,
           editor: new fm.NumberField({
               allowNegative: false,
               maxValue: 100000,
               decimalPrecision:1
           })
        },{
           header: "重量9",
           dataIndex: 'weight9',
           width: 60,
           align: 'right',
           //renderer: formatDate,
           editor: new fm.NumberField({
               allowNegative: false,
               maxValue: 100000,
               decimalPrecision:1
           })
        },{
           header: "重量10",
           dataIndex: 'weight10',
           width: 60,
           align: 'right',
           //renderer: formatDate,
           editor: new fm.NumberField({
               allowNegative: false,
               maxValue: 100000,
               decimalPrecision:1
           })
        }
    ]);

    // by default columns are sortable
    cm.defaultSortable = true;

    // create the Data Store
    store = new Ext.data.Store({
        // the return will be XML, so lets set up a reader
        reader: new Ext.data.XmlReader({
               // records will have a "plant" tag
               record: 'plant'
           }, Plant),

        sortInfo:{field:'productName', direction:'ASC'}
    });

    // create the editor grid
    grid = new Ext.grid.EditorGridPanel({
        store: store,
        cm: cm,
        //renderTo: 'editor-grid',
        //width:1000,
        height:350,
        autoExpandColumn:'productName',
        title:'商品列表',
        frame:true,
        //plugins:checkColumn,
        clicksToEdit:1,
		trackMouseOver:false,
        disableSelection:true,
        loadMask: {msg:'正加载数据...'},
        viewConfig: {
            forceFit:true            
        },
        tbar: [{
            text: '添加',
            pressed: true,
            handler : function(){
                addNew();
            }
        },'-',{
            text: '删除',
            pressed: true,
            handler : function(){
                if(row != -1){
                	store.removeAt(row);
                	row = -1;
                }
            }
        },'-',{
            text: '小计',
            pressed: true,
            handler : function(){
                calculateSummary();
            }
        },'-','<4mm',{
            xtype:'textfield',
            name: 'lThan',fieldLabel: '小于3.5cm', id:'lThan',
            anchor:'95%'
        },'-','4mm',{
            xtype:'textfield',
            name: 'eThan',fieldLabel: '小于等于4mm', id:'eThan',
            anchor:'95%'
        },'-','>4mm',{
            xtype:'textfield',
            name: 'bThan',fieldLabel: '大于4cm', id:'bThan',
            anchor:'95%'
        }]
    });
    grid.on('keypress',down);
    grid.on('rowclick',clickrow);
    
    var addform={
    	url:'dws!add.do',
    	id:'addform',
    	xtype:'form',
    	height:300,
   		usepurse:'addform', //用途,默认情况下是添加，也可以是modifyform
   		labelWidth:65,labelAlign:'right',
       	baseCls:"x-plain",style:"padding:5px",
        items:[{
                xtype:'textfield',
                name:'cusName',fieldLabel: '客户名称', id:'cusName',
                allowBlank:false,
                anchor:'95%'
            },{
                xtype:'textfield',
                name: 'linker',fieldLabel: '取货人', id:'linker',
                anchor:'95%'
            },{
                xtype:'textfield',
                name: 'phoneNo',fieldLabel: '取货人电话', id:'phoneNo',
                anchor:'95%'
            },{
                xtype:'textfield',
                name: 'productCount',fieldLabel: '件数', id:'productCount',
                anchor:'95%'
            },{
                xtype:'textfield',
                name: 'tCount',fieldLabel: '总重量', id:'tCount',
                anchor:'95%'
            },{
                xtype:'textfield',
                name: 'tPrice',fieldLabel: '总价', id:'tPrice',
                anchor:'95%'
            },
            new Ext.form.TriggerField({
		       fieldLabel: '出货日期',
		       name: 'outTime',
		       id: 'outTime',
		       width: 150,
		       anchor:'99%',
		       readOnly: true,
		       triggerClass: 'x-form-date-trigger',emptyText:'请选择日期....',
		       listeners:{
			      'render':function()
			      {
			           Ext.EventManager.on("outTime", 'click', function(){
			               new  WdatePicker({
			                    skin: 'ext',                            // 应用ext的皮肤样式
			                    dateFmt: 'yyyy-MM-dd HH:mm:ss'                   // 格式为：年-月
			                 });
			          })
			      }
			     }
			}),{
			xtype:'panel',
        	layout:"column",baseCls:"x-plain",style:"padding:5px",
        	items:[{
        		columnWidth:.25,layout:"form",labelWidth:50,baseCls:"x-plain",
            	items:[
            		new Ext.Button({
            			text:'计算',
            			handler : function(){
                			calculateSummary();
            			}
            		})
            	]
           },{
        		columnWidth:.25,layout:"form",labelWidth:50,baseCls:"x-plain",
            	items:[
 					new Ext.Button({
            			text:'保存',
            			handler : function(){
                			save();
            			}
            		})           	
            	]
           },{
        		columnWidth:.25,layout:"form",labelWidth:50,baseCls:"x-plain",
            	items:[
 					new Ext.Button({
 						id:'printBtn',
            			text:'导出',
            			disabled:'true',
	        	    	   handler:function(){
	        	    		   window.open(contextRootPath+'/product/export.do?productId='+productId);
	        	    	   }
            		})           	
            	]
           },{
	       		columnWidth:.25,layout:"form",labelWidth:50,baseCls:"x-plain",
	        	items:[
	        	       new Ext.Button({
	        	    	   text:'重置'
	        	       })           	
	        	]
	       }]
        }]    
    };
    
    var viewport = new Ext.Viewport({   //视图
           layout:'border',
           items:[{
		        region: 'center',
		        items:[grid,sumGrid]
		    }, {
		        region: 'west',
		        collapsible: true,
		        height: 300,
		        width:300,
		        frame:true,
		        //minHeight: 100,
		        items:addform
		    }]
        });   
	 grid.render();
	 sumGrid.render();
	 addNew();

});

Ext.grid.CheckColumn = function(config){
    Ext.apply(this, config);
    if(!this.id){
        this.id = Ext.id();
    }
    this.renderer = this.renderer.createDelegate(this);
};

Ext.grid.CheckColumn.prototype ={
    init : function(grid){
        this.grid = grid;
        this.grid.on('render', function(){
            var view = this.grid.getView();
            view.mainBody.on('mousedown', this.onMouseDown, this);
        }, this);
    },

    onMouseDown : function(e, t){
        if(t.className && t.className.indexOf('x-grid3-cc-'+this.id) != -1){
            e.stopEvent();
            var index = this.grid.getView().findRowIndex(t);
            var record = this.grid.store.getAt(index);
            record.set(this.dataIndex, !record.data[this.dataIndex]);
        }
    },

    renderer : function(v, p, record){
        p.css += ' x-grid3-check-col-td'; 
        return '<div class="x-grid3-check-col'+(v?'-on':'')+' x-grid3-cc-'+this.id+'">&#160;</div>';
    }
};